package twentytwentyone_3;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Zahi
 * @Description:
 * @Date Created in 2021-03-15 12:11
 * @Modified By:
 */
public class ReverseStr_541 {
    public static void main(String[] args){
        String s = "abcdef";
        System.out.println(reverseStr(s, 3));
    }

    public static String reverseStr(String s,int k){
        List<String> arr = new ArrayList<>();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i += 2*k) {
            // 将s以2k作为步长进行分割，存入arr中
            if (i + 2*k < s.length()){
                arr.add(s.substring(i, i + 2*k));
            }else {
                arr.add(s.substring(i));
            }
        }
        for (String s1 : arr) {
            if (s1.length() > k){
                // 对于比k长的，前k位倒序拼接
                for (int j = k - 1; j >= 0; j--) {
                    result.append(s1.charAt(j));
                }
                // 后k位正常拼接
                for (int j = k; j < s1.length(); j++) {
                    result.append(s1.charAt(j));
                }
            }else {
                // 最后的尾部如果是比k短的，直接全部倒序拼接
                for (int i = s1.length() - 1; i >= 0; i--) {
                    result.append(s1.charAt(i));
                }
            }
        }
        return result.toString();
    }
}
